<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 18px 22px 22px 22px;
  background-color: rgb(240, 242, 245);
  margin-bottom: 80px;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.form-operator-button {
  background-color: #fff;
  position: fixed;
  width: 100%;
  left: 0px;
  right: 0;
  bottom: 33px;
  height: 64px;
  line-height: 64px;
  text-align: right;
  box-shadow: 0 -1px 2px 0 rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.form-el-radion {
  line-height: 30px;
  padding: 5px 0px;
  width: 100%;
}

.hex-form-inf {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  cursor: pointer;
  margin-right: 40px;
  position: relative;
  min-height: 33px;
  margin-left: 60px;
  line-height: 33px;
}

.hex-form-inf-content {
  font-size: 14px;
  font-weight: 500;
  display: none;
}

.hex-form-inf-icon {
  font-size: 20px;
  margin-top: 5px;
  position: absolute;
  right: 0px;
}
</style>
<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <el-card class="box-card" v-if="showType == true">
        <div slot="header" class="clearfix">
          <span>实例列表</span>
        </div>
        <!--工具栏-->
        <div class="head-container">
          <crudOperation :permission="permission" :defaultQueryForm="defaultQueryForm"
                         :moreQueryList="moreQueryList" :allApp="allApp"/>
        </div>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data"
                  :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                  row-key="id" @select="crud.selectChange" @select-all="crud.selectAllChange"
                  @selection-change="crud.selectionChangeHandler"
                  @filter-change="crud.handleFilterChange" @row-dblclick="goTaskInfo"
                  :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border stripe>
          <el-table-column v-if="columns.visible('bizDate')" :show-overflow-tooltip="true" label="业务日期" align="center"
                           prop="bizDate"/>
          <el-table-column v-if="columns.visible('jobName')" :show-overflow-tooltip="true" label="作业名称(编码)"
                           min-width="120"
                           align="center" prop="jobName" :formatter="formattertaskName"/>
          <el-table-column v-if="columns.visible('appCode')" :show-overflow-tooltip="true" label="应用编码" align="center"
                           prop="appCode"/>
          <el-table-column v-if="columns.visible('jobStatus')" prop="jobStatus" label="状态"
                           :formatter="jobStatusFormatter" key="jobStatus"
                           align="center" :filters="cyclejobStatusDict"
                           filter-placement="bottom-end" :filter-multiple="false" column-key="jobStatus">
            <template slot-scope="scope">
              <el-tag size="small" :type="cyclejobStatusFormatterType(scope.row.jobStatus)" style="width:60px;">
                {{ cyclejobStatusFormatter(scope.row.jobStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="columns.visible('taskStatusCount')" align="center" min-width="100"
                           :show-overflow-tooltip="true" label="任务统计" prop="taskStatusCount"/>
          <el-table-column v-if="columns.visible('sortNo')" align="center" min-width="100" :show-overflow-tooltip="true"
                           label="优先级" prop="sortNo"/>
          <el-table-column v-if="columns.visible('jobStTs')" align="center" min-width="160"
                           :show-overflow-tooltip="true"
                           label="开始执行时间" prop="jobStTs"/>
          <el-table-column v-if="columns.visible('jobEndTs')" align="center" min-width="160"
                           :show-overflow-tooltip="true"
                           label="执行结束时间" prop="jobEndTs"/>
          <el-table-column v-if="columns.visible('costTs')" align="center" min-width="160" :show-overflow-tooltip="true"
                           label="耗时" prop="costTs"/>
          <el-table-column v-if="columns.visible('upTs')" align="center" min-width="160" :show-overflow-tooltip="true"
                           label="更新时间" prop="upTs"/>
          <el-table-column v-if="columns.visible('crtTs')" align="center" min-width="160" :show-overflow-tooltip="true"
                           label="创建时间" prop="crtTs"/>

        </el-table>
      </el-card>
      <SysTaskInfo ref="stInfo" :goBack="goBack" :jobCode="this.jobCode"/>
    </div>
    <!-- 数据备份 -->
    <el-dialog append-to-body :close-on-click-modal="false" :visible.sync="crud.backUp" title="作业实例备份" width="680px">
      <el-form ref="form" :inline="true" :model="form" size="small" label-width="160px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="备份日期">
              <el-date-picker style="margin-left: 50px" v-model="backUpDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-document-delete" @click="backUpCancel()">取消</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="backUpSubmit()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import crudOperation from '@crud/extend/cycleTask/cycleJob/admin/CRUD.operation'
import job from '@/api/cycleJob/job'
import SysTaskInfo from '../../cycleTask/admin'
import config from '@/settings'
import backUp from '@/api/backUp/backUp'
import appConfApi from '@/api/app/app'

const isDefBizDate = config.isDefBizDate
const dateOffset = config.dateOffset

// crud交由presenter持有
const queryList = [{
  cloumValue: 'jobCode',
  cloumName: '作业编码'
}, {
  cloumValue: 'jobName',
  cloumName: '作业名称'
},
  {
    cloumValue: 'appCode',
    cloumName: '应用编码'
  }, {
    cloumValue: 'bizDate',
    cloumName: '业务日期'
  }
]
const defaultCrud = CRUD({
  title: '作业实例',
  url: 'api/periodJob',
  queryList: queryList,
  queryOnPresenterCreated: false,
  crudMethod: {
    ...job
  },
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false
  }
})
const defaultForm = {}
export default {
  name: 'job',
  components: {
    crudOperation,
    SysTaskInfo
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['cycle_job_status'],
  data() {
    return {
      backUpDate: "",
      menus: [],
      jobCode: '',
      active: 0,
      showType: true,
      dataList: [],
      taskDataList: [],
      allApp: [],
      taskForm: {
        taskCode: '',
        taskName: '',
        shellPath: '',
        shellParam: '',
        weight: '',
        errCount: '',
        isEndTask: true,
        isOrder: true
      },
      defaultQueryForm: {
        jobCode: null,
        jobName: null,
        jobStatus: '',
        bz: null,
        startTime: [],
        endTime: [],
        jobCodes: null,
        appCode: null
      },
      moreQueryList: [
        {
          cloumLable: 'jobCodeFuzzy',
          name: '作业编码',
          type: 'textarea',
          placeholder: '请输入支持单个或批量作业编码模糊查询，用逗号隔开',
          defaultValue: null
        },
        {
          cloumLable: 'jobNameFuzzy',
          name: '作业名称',
          type: 'textarea',
          placeholder: '请输入支持单个或批量作业名称模糊查询，用逗号隔开',
          defaultValue: null
        },
        {cloumLable: 'appCode', name: '应用编码', type: 'input', placeholder: '', defaultValue: null},
        {
          cloumLable: 'jobStatus', name: '作业状态', type: 'radio', placeholder: '', defaultValue: null, radioList: [
            {label: '', value: '全部'},
            {label: '1', value: '未完成'},
            {label: '4', value: '已完成'}
          ]
        },
        {
          cloumLable: 'bz',
          cloumLableType: 'bzType',
          name: '业务日期',
          type: 'dateNoTimePicker',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'startTime',
          cloumLableType: 'startTimeType',
          name: '开始时间',
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        },
        {
          cloumLable: 'endTime',
          cloumLableType: 'endTimeType',
          name: '结束时间',
          type: 'timeFramePicker',
          placeholder: '',
          defaultValue: null
        }
      ],
      permission: {
        backUp: ['cycleJob:backUp']
      },
      cyclejobDict: [],
      cyclejobStatusDict: []
    }
  },
  created() {
    this.active = 0
    this.crud.optPageShow.addPage = false
    this.cyclejobDict = this.dict.cycle_job_status;
    this.init()
    this.initAppCodes()
  },
  watch: {
    cyclejobDict() {
      this.$nextTick(() => {
        this.cyclejobDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.cyclejobStatusDict.push(obj)
        })
      })
    },
  },
  methods: {
    init() {
      this.crud.query.bizDate = this.currentDate()
      this.crud.toQuery()
    },
    initAppCodes() {
      let param = {size: 1000000000}
      appConfApi.selectPages(param)
        .then(res => {
          if (res && res.total > 0) {
            this.allApp = res.content;
          }
        });
    },
    cyclejobStatusFormatterType(val) {
      const type = ['', 'info', 'primary', 'warning', 'success', 'danger']
      return type[val]
    },
    cyclejobStatusFormatter(val) {
      return this.dict.label.cycle_job_status[val]
    },
    currentDate() {
      let timestamp = Date.now() + dateOffset * 1000 * 60 * 60 * 24
      let date = new Date(timestamp)
      let year = date.getFullYear()
      let month = ('0' + (date.getMonth() + 1)).slice(-2)
      let sdate = ('0' + date.getDate()).slice(-2)
      let result = year + month + sdate
      return result
    },
    formattertaskName(val) {
      return val.jobName + "(" + val.jobCode + ")"
    },
    formatterCostTs(val) {
      var date1 = new Date(val.jobStTs)
      var date2 = new Date(val.jobEndTs)
      var s1 = date1.getTime(),
        s2 = date2.getTime();
      var total = (s2 - s1) / 1000;
      var hour, minute, second, module
      if (total >= 3600) {
        hour = parseInt(total / 3600)
        module = parseInt((total - hour * 60 * 60) / 60)
        return hour + "时" + module + "分"
      } else if (total >= 60 && total < 3600) {
        minute = parseInt(total / 60)
        module = parseInt((total - minute * 60) / 60)
        return minute + "分" + module + "秒"
      } else {
        second = total
        return second + "秒"
      }
    },
    backUpCancel() {
      this.crud.backUp = false
      this.backUpDate = ""
    },
    backUpSubmit() {
      var data = {
        "dateTs": this.backUpDate,
        "bitchType": "cycle"
      }
      backUp.backUpData(data)
        .then(() => {
          this.$notify({
            title: '成功',
            message: '数据备份成功',
            type: 'success'
          });
          this.backUpDate = ""
          this.crud.backUp = false
          this.crud.query = {}
          this.crud.params = {}
          this.crud.toQuery()
        })
        .catch(() => {
          this.$notify.error({
            title: '错误',
            message: '数据备份异常'
          });
        });
    },
    jobStatusFormatter(val) {
      return this.dict.label.cycle_job_status[val]
    },
    formatterjobStatusType(val) {
      const type = ['', 'info', 'primary', 'warning', 'success', 'danger']
      return type[val]
    },
    goTaskInfo(row, column, event) {
      this.showType = false
      this.jobCode = row.jobCode
      let jobInf = {
        pkId: row.pkId,
        jobCode: row.jobCode,
        bizDate: row.bizDate
      }
      this.$refs.stInfo.initQry(jobInf)
    },
    goBack() {
      this.showType = true
      this.crud.refresh()
    }
  }
}
</script>
